class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :store_previous_url

  helper_method :current_user

  def require_login
    (redirect_to login_path, error: '请您先登陆，再进行当前操作！') && return unless current_user
    raise ActionController::RoutingError, 'Not Found' unless current_user.role == :admin
  end

  def require_staff
    current_user.update(role: :admin) if current_user && current_user.normal_user? && current_user.is_admin_in_geekpark?
    redirect_to root_path, error: '您的操作需要管理员权限！' unless current_user && !current_user.normal_user?
  end

  def current_user
    @current_user ||= from_session || from_cookies
  end

  def store_previous_url
    session[:previous_url] = request.fullpath
  end

  def redirect_back_or_default default_url
    redirect_to previous_url_or_default(default_url)
  end

  def previous_url_or_default default_url
    session[:previous_url] || default_url
  end

  def from_session
    User.find_by(id: session[:user_id]) if session[:user_id]
  end

  def from_cookies
    user = User.find_by(remember_token: cookies[:remember_token]) if cookies[:remember_token]
    if user && user.remember_token_created_at > 1.days.ago
      session[:user_id] = user.id
      user
    else
      cookies.delete :remember_token
      nil
    end
  end

  def available_years
    ['2015', '2016']
  end

  def enable_layout
    current_year = available_years.include?(params[:year]) ? params[:year] : available_years.last
    "Innoawards_#{current_year}"
  end

end
